#!/usr/bin/python
# -*- coding:utf-8 -*-

"""
通过用户提供的API向外推送消息
"""
import json

import requests
from requests.exceptions import RequestException
from requests.auth import HTTPBasicAuth
from app.libs.json_helper import DateTimeEncoder


def send_message(data, url_obj=None, url=None, method=None, auth_type=None,
                 auth_key=None, auth_value=None, add_to=None):
    """
    data: 消息内容
    url_obj: OutPutConfig 实例
    url: 接收消息的url
    method: 请求方式  GET 或者 POST
    auth_type: 认证方式 api_key，basic_auth， no_auth
    auth_key: 认证key
    auth_value: 认证value
    add_to: 目前仅支持在header中自定义key， value
    """
    if url_obj and (not url_obj.is_active):
        return False, "推送被禁用"
    if url_obj:
        url = url_obj.url
        method = url_obj.method
        auth_type = url_obj.auth_type
        auth_key = url_obj.auth_key
        auth_value = url_obj.auth_value
        add_to = url_obj.add_to
    assert method in ["GET", "POST"]
    assert auth_type in ["api_key", "basic_auth", "no_auth"]
    assert add_to in ["header", "basic_auth", "no_auth"]
    session = requests.session()
    if auth_type == "basic_auth":
        session.auth = HTTPBasicAuth(username=auth_key, password=auth_value)
    elif auth_type == "api_key" and add_to == "header":
        session.headers.update({auth_key: auth_value})
    data = json.dumps({"data": data}, cls=DateTimeEncoder)
    headers = {"content-type": "application/json"}
    try:
        if method == "GET":
            response = session.get(url=url, data=data, verify=False, timeout=30, headers=headers)
        else:
            response = session.post(url=url, data=data, verify=False, timeout=30, headers=headers)
    except RequestException:
        return False, "推送失败， URL连接错误"
    if 200 <= response.status_code <= 299:
        return True, "推送成功"
    else:
        return False, response.text
